<?php

	/**
	 * Workspace@ Engine application comment!
	 * 
	 * LICENSE
	 * This application is licensed under New BSD license.
	 * Please read complete LICENSE.txt inside of root folder for more details.
	 * 
	 * We wish you good building :) 
	 * 
	 * @category   Application
	 * @package    Bootstrap
	 * @author     Nevio Vesic <nevio@workspaceat.com>
	 * @copyright  2008-2009 Workspace@ group in association with Design strategist
	 */

	class Engine_Plugins_Storage extends Engine_Application_Abstract
	{

		protected $db          = null;
		
		protected static $storage_loc = null;
		protected static $image_loc   = null;
		protected static $files_loc   = null;
		protected static $mixed_loc   = null;
		protected static $videos_loc  = null; 
		protected static $baseloc     = null;
		function __construct()
		{
			
			$this->db = $this->databaseInstance();
			
			# lets set storage paths
			$this->setLocations();
		}
		
		/**
		 * Set storage base locations
		 */
		private function setLocations()
		{
			if ( self::$storage_loc )
			{
				self::$storage_loc = null;
			}
			
			if ( self::$baseloc )
			{
				self::$baseloc = null;
			}

			if ( self::$image_loc )
			{
				self::$image_loc = null;
			}
			
			if ( self::$files_loc )
			{
				self::$files_loc = null;
			}
			
			if ( self::$mixed_loc )
			{
				self::$mixed_loc = null;
			}	
			
			if ( self::$videos_loc )
			{
				self::$videos_loc = null;
			}
			
			self::$baseloc     = self::$system -> enviroment -> url . self::$system -> enviroment -> access -> element;
			self::$storage_loc = self::$system -> storage -> location;
			self::$files_loc   = self::$system -> storage -> files   -> location;
			self::$videos_loc  = self::$system -> storage -> videos  -> location;
			self::$image_loc   = self::$system -> storage -> images  -> location;
		}
		
		/**
		 * Load javascript template and return data for json;
		 *
		 * @param array $data
		 */
		public function addGroup( Zend_Config $params )
		{
			if (! $params -> name )
			{
				return array (
					"status" => "false",
					"input"  => "name",
					"message" => "Group name must be specified!"
				);
				die();
			}
			
			if (! $params -> tags )
			{
				return array (
					"status" => "false",
					"input"  => "tags",
					"message" => "Tags for current group must be specified!"
				);
				die();
			}
			
			if (! $params -> status )
			{
				return array (
					"status" => "false",
					"input"  => "status",
					"message" => "Status for current group must be specified!"
				);
				die();
			}			
			
			if (! $params -> type )
			{
				return array (
					"status" => "false",
					"input"  => "type",
					"message" => "Type for current group must be specified!"
				);
				die();
			}
			
			if (! $params -> description || strlen( $params -> description ) < 5 )
			{
				return array (
					"status" => "false",
					"input"  => "description",
					"message" => "Description must be specified and bigger than 5 chars!"
				);
				die();
			}
			
			# ok it passes all tests, lets now create the rest :)
			$unixname = $this->replaceChars( $params -> name );
			
			if ( eregi ( ",", $params -> tags ) )
			{
				$arr = split(",", $params -> tags );
				
				foreach ( $arr as $keys )
				{
					if ($keys !== " " )
					{
						$tags_data .= $keys .", ";
					}
				}
				
			}else
			{
				$tags_data = $params -> tags;	
			}

			# lets now checkout if current group already exists
			$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
			
			$result = $this->db->fetchRow("SELECT id FROM storage_groups WHERE name='{$params -> name}' AND type='{$params->type}' " );
	
			if ( $result->id )
			{
				return array (
					"status" => "false",
					"input"  => "",
					"message" => "Current group already exists inside of system!"
				);
				die();
			}
			
			# ok lets continue now
			if ( $params -> type == "images" )
			{
				$current_loc = self::$image_loc . $unixname;
			}
			elseif ( $params -> type == "files" )
			{
				$current_loc = self::$files_loc . $unixname;
			}
			elseif ( $params -> type == "videos" )
			{
				$current_loc = self::$videos_loc . $unixname;
			}
			elseif (  $params -> type == "mixed" )
			{
				$current_loc = self::$mixed_loc . $unixname;
			}
			else
			{
				return array (
					"status" => "false",
					"input"  => "",
					"message" => "{$params -> type} isn't valid group type... Hmm interesting error lol!"
				);
				die();
			}
			
			if (! is_dir( $current_loc ) )
			{
				$a = mkdir($current_loc, 0755 );
				$ab = fopen($current_loc.DIRECTORY_SEPARATOR."index.html", "a+", true );
				fclose($ab);
				if (! $a )
				{
					return array (
						"status" => "false",
						"input"  => "",
						"message" => "Group folder can't be created! Fatal error!"
					);
				}
			}
			
			# ok lets add sql query
			$results = $this->db->query ( "INSERT INTO storage_groups ( garbaged, name, unixname, tags, description, type, status, lastmodification, createdat )
										   VALUES ( 'false', '{$params->name}', '{$unixname}', '{$tags_data}', '{$params->description}', '{$params->type}',
										            '{$params->status}', NOW(), NOW() )" );
			if (! $results )
			{
				return array (
					"status" => "false",
					"input"  => "",
					"message" => "There was a problem with SQL insertation. Server doesn't response!"
				);
				die();
			}
			else
			{
				return array (
					"status" => "true",
					"input"  => "",
					"doPostAction" => "true",
					"message" => "Group has been added successfully! Please wait..."
				);
			}
		}
		
		/**
		 * Stupid function for replacing illegal characters with "" and white spaces with -
		 *
		 * @param  string $str
		 * @return string
		 */
		private function replaceChars($str)
		{
			$a = str_replace("`", "", $str );
			$b = str_replace("~", "", $a   );
			$c = str_replace("`", "", $b   );
			$d = str_replace("!", "", $c   );
			$e = str_replace("@", "", $d   );
			$f = str_replace("#", "", $e   );
			$g = str_replace("$", "", $f   );
			$h = str_replace("%", "", $g   );
			$i = str_replace("^", "", $h   );
			$j = str_replace("&", "", $i   );
			$k = str_replace("*", "", $j   );
			$l = str_replace("(", "", $k   );
			$m = str_replace(")", "", $l   );
			$n = str_replace("}", "", $m   );
			$o = str_replace("{", "", $n   );
			$p = str_replace("[", "", $o   );
			$r = str_replace("]", "", $p   );
			$s = str_replace(":", "", $r   );
			$t = str_replace("\\", "", $s   );
			$u = str_replace("/", "", $t   );
			$v = str_replace("'", "", $u   );
			$x = str_replace("\"", "", $v   );
			$y = str_replace("|", "", $x   );
			$z = str_replace("<", "", $y   );
			$a1 = str_replace(">", "", $z   );
			$a2 = str_replace(";", "", $a1   );
			$a3 = str_replace(" ", "-", $a2   );
			$a4 = str_replace("=", "", $a3   );
			$a5 = str_replace(",", "", $a4   );
			$a6 = str_replace(".", "_", $a5   );
			return $a6;
		}
		
		public function modifyGroup( Zend_Config $params, $id )
		{
			if (! $params -> name )
			{
				return array (
					"status" => "false",
					"input"  => "name",
					"message" => "Group name must be specified!"
				);
				die();
			}
			
			if (! $params -> tags )
			{
				return array (
					"status" => "false",
					"input"  => "tags",
					"message" => "Tags for current group must be specified!"
				);
				die();
			}
			
			if (! $params -> status )
			{
				return array (
					"status" => "false",
					"input"  => "status",
					"message" => "Status for current group must be specified!"
				);
				die();
			}			
			
			if (! $params -> type )
			{
				return array (
					"status" => "false",
					"input"  => "type",
					"message" => "Type for current group must be specified!"
				);
				die();
			}
			
			if (! $params -> description || strlen( $params -> description ) < 5 )
			{
				return array (
					"status" => "false",
					"input"  => "description",
					"message" => "Description must be specified and bigger than 5 chars!"
				);
				die();
			}
			
			# ok it passes all tests, lets now create the rest :)
			$unixname = $this->replaceChars( $params -> name );
			
			if ( eregi ( ",", $params -> tags ) )
			{
				$arr = split(",", $params -> tags );
				
				foreach ( $arr as $keys )
				{
					if ($keys !== " " )
					{
						$tags_data .= $keys .", ";
					}
				}
				
			}else
			{
				$tags_data = $params -> tags;	
			}

			# lets now checkout if current group already exists
			$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
			
			$result = $this->db->fetchRow("SELECT * FROM storage_groups WHERE id='{$id}' " );
	
			if ( $result->id )
			{
			
				# ok lets continue now
				if ( $params -> type == "images" )
				{
					$current_loc = self::$image_loc . $unixname;
					$existing_loc = self::$image_loc . $result -> unixname;
				}
				elseif ( $params -> type == "files" )
				{
					$current_loc = self::$files_loc . $unixname;
					$existing_loc = self::$files_loc . $result -> unixname;
				}
				elseif ( $params -> type == "videos" )
				{
					$current_loc = self::$videos_loc . $unixname;
					$existing_loc = self::$videos_loc . $result -> unixname;
				}
				elseif (  $params -> type == "mixed" )
				{
					$current_loc = self::$mixed_loc . $unixname;
					$existing_loc = self::$mixed_loc . $result -> unixname;
				}
				else
				{
					return array (
						"status" => "false",
						"input"  => "",
						"message" => "{$params -> type} isn't valid group type... Hmm interesting error lol!"
					);
					die();
				}
				echo $result -> unixname;
				if ( $result -> unixname !== $unixname )
				{
					if (! is_dir( $current_loc ) )
					{
						
						$a = copy( $existing_loc, $current_loc );

						if (! $a )
						{
							return array (
								"status" => "false",
								"input"  => "",
								"message" => "Group folder can't be replaced! Fatal error!"
							);
						}
					}
				}
				
				# ok lets add sql query
				$results = $this->db->query ( "UPDATE storage_groups
												SET 
												garbaged = 'false',
												name = '{$params->name}',
												unixname = '{$unixname}',
												tags  = '{$tags_data}',
												description = '{$params->description}',
												type = '{$params->type}',
												status = '{$params->status}',
												lastmodification = NOW(),
												createdat = NOW()
											   WHERE ( id='{$id}')" );
				if (! $results )
				{
					return array (
						"status" => "false",
						"input"  => "",
						"message" => "There was a problem with SQL update. Server doesn't response!"
					);
					die();
				}
				else
				{
					return array (
						"status" => "true",
						"input"  => "",
						"doPostAction" => "true",
						"message" => "Group has been successfully updated! Please wait..."
					);
				}
			}
		}
		/**
		 * Replace whitespace with ,
		 *
		 * @param  string $elm
		 * @return string
		 */
		private function replaceWhitespace($elm)
		{
			$a = str_replace( " ", ",", $elm );
			return $a;
		}
		
		/**
		 * Get existing non-garbaged groups
		 *
		 * @return Zend_Db
		 */
		public function getGroupsList(){
			
			$result = $this->db->fetchAll("SELECT id, name, unixname, type FROM storage_groups WHERE garbaged='false' " );
			return $result;
		}
		
		public function getAllActiveImageGroups()
		{
			$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
			
			$result = $this->db->fetchAll ( "SELECT * FROM storage_groups WHERE garbaged='false' AND type='images'" );
			
			return $result;
		}
		/**
		 * Fetch only one row from groups by their id!
		 *
		 * @param  int $id
		 * @return Object[Zend_Db]
		 */
		public function getGroupById($id){
			$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
			$result = $this->db->fetchRow("SELECT * FROM storage_groups WHERE id='{$id}' " );
			return $result;
		}
		
		public function garbageExistingGroup($id, $name)
		{
			# ok lets go check if current group got any of id's
			$aresult = $this->db->query ("UPDATE storage_images 
								SET
									garbaged = 'true'
								WHERE groupid='{$id}'" );
								
			$bresult = $this->db->query ("UPDATE storage_videos
								SET
									garbaged = 'true'
								WHERE groupid='{$id}'" );
								
			$cresult = $this->db->query ("UPDATE storage_files
								SET
									garbaged = 'true'
								WHERE groupid='{$id}'" );

			$dresult = $this->db->query ("UPDATE storage_groups
								SET
									garbaged = 'true'
								WHERE id='{$id}' AND unixname='{$name}'" );
								
			if( $aresult && $bresult && $cresult && $dresult )
			{
				return array (
					"status" => "true",
					"message" => "Group content successfuly garbaged! Group deleted! Please wait..."
				);
			}
			
			return array (
				"status" => "false",
				"message" => "Group sql error! Can't be deleted!"
			);
		}
		
		public function addAboutImage( Zend_Config $data )
		{
			$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
			if (! $data-> name )
			{
				return array (
					"status"  => "false",
					"message" => "You must enter image name!",
					"input"   => "name"
				);
				die();
			}
			
			if (! $data-> tags )
			{
				return array (
					"status"  => "false",
					"message" => "You must enter tags to image splited by , or ;",
					"input"   => "tags"
				);
				die();
			}

			if ( $data-> group == "0" )
			{
				return array (
					"status"  => "false",
					"message" => "You must choose group for image!",
					"input"   => "group"
				);
				die();
			}
			
			if ( strlen( $data-> description ) < 5 )
			{
				return array (
					"status"  => "false",
					"message" => "You must enter description for image!",
					"input"   => "description"
				);
				die();
			}
			
			$unixname = $this->replaceChars( $data -> name );
			
			// ok lets add image
			$query = $this->db->query("INSERT INTO storage_images ( 
			name, 
			unixname, 
			groupid, 
			garbaged, 
			tags, 
			description, 
			status, 
			createdat 
			) VALUES ( 
			'{$data->name}', 
			'{$unixname}', 
			'{$data->group}', 
			'false', 
			'{$data->tags}', 
			'{$data->description}', 
			'{$data->status}',
			 NOW() 
			 )" );
			
			if ( $query )
			{
				$q2 = "SELECT id FROM storage_images WHERE unixname='{$unixname}'";
				
				$result = $this->db->fetchRow( $q2 );
				
				if ( $result->id )
				{
					$string = "storage/manage/images/upload/:{$unixname}/:{$result->id}";
					
					return array (
						"status"   => "true",
						"message"  => "You must enter description for image!",
						"task"    => "finish",
						"location" => "{$string}"
					);
					die();
				}
				else
				{
					return array (
						"status"  => "false",
						"message" => "There was a problem with SQL. Please contact support!",
					);
					die();
				}
			}
		}
		
		public function modifyAboutImage( Zend_Config $data )
		{
			$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
			if (! $data-> name )
			{
				return array (
					"status"  => "false",
					"message" => "You must enter image name!",
					"input"   => "name"
				);
				die();
			}
			
			if (! $data-> tags )
			{
				return array (
					"status"  => "false",
					"message" => "You must enter tags to image splited by , or ;",
					"input"   => "tags"
				);
				die();
			}

			if ( $data-> group == "0" )
			{
				return array (
					"status"  => "false",
					"message" => "You must choose group for image!",
					"input"   => "group"
				);
				die();
			}
			
			if ( strlen( $data-> description ) < 5 )
			{
				return array (
					"status"  => "false",
					"message" => "You must enter description for image!",
					"input"   => "description"
				);
				die();
			}
			
			$result = $this->db->fetchRow( "UPDATE storage_images SET
				name='{$data->name}',
				unixname='{$unixname}',
				groupid='{$data->groupid}'" );
			
			if ( $result->id )
			{
				$string = "storage/manage/images/upload/:{$unixname}/:{$result->id}";
				
				return array (
					"status"   => "true",
					"message"  => "You must enter description for image!",
					"task"    => "finish",
					"location" => "{$string}"
				);
				die();
			}
			else
			{
				return array (
					"status"  => "false",
					"message" => "There was a problem with SQL. Please contact support!",
				);
				die();
			}
		}
		
		public function uploadImage( $data )
		{
			if ( $data["name"] )
			{
				
				if ( strlen( $data["name"] ) < 3 )
				{
					return array (
						"status"  => "false",
						"message" => "As we said Fake name must not be smaller than 3 chars!",
						"input"   => "fakename"
					);
					die();
				}
				$unixname = $this->replaceChars( $data['name'] );
			}
			else
			{
				$unixname =  false;
			}
			
			if(! $data['image'] )
			{
				return array (
					"status"  => "false",
					"message" => "Image must be specified! Please choose image!",
					"input"   => "image"
				);
				die();
			}
			
			// lets check image type
			
			$legal = array (
				"image/png",
				"image/jpeg",
				"image/bmp",
				"image/jpg",
				"image/tif"	
			);
			
			if (! in_array($data['image']['type'], $legal ))
			{
				return array (
					"status"  => "false",
					"message" => "Unsuported file type. PNG - JPEG - BMP  are allowed!",
					"input"   => "image"
				);
				die();
			}
			
			
			// ok we are now ready to see what's next
			$loc = self::$image_loc .  $data["id"] .DIRECTORY_SEPARATOR;
			
			if (! is_dir ( $loc ) )
			{
				// lets go attempt to create directory!
				if (! mkdir( $loc, 0644 ) )
				{
					return array (
						"status"  => "false",
						"message" => "There was error with creating directory. Please contact support!",
						"input"   => "image"
					);
					die();
				}
			}
			
			// Ok we got directory
			// lets go upload it to server
			// first lets do faken image name...
			$split = explode( ".", $data['image']['name']);
			
			if ($unixname == false)
			{
				$filename = rand(1, 10000000) . "_" . $split[0] . "." . $split[1];	
			}
			else
			{
				$filename = $unixname . "." . $split[1];
			}
			
			$loc = $loc . $filename;
			 
			if (! is_uploaded_file( $loc ) )
			{
				if ( move_uploaded_file($data['image']['tmp_name'], $loc ) )
				{
					
					// jaj lets go add sql query for this one...
					$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
					
					$result = $this->db->query("INSERT INTO storage_images_data (
					imageid,
					garbaged,
					fakename,
					filename,
					size,
					type,
					status,
					createdat
					) VALUES (
					'{$data['id']}',
					'false',
					'{$unixname}',
					'{$filename}',
					'{$data['image']['size']}',
					'{$split[1]}',
					'true',
					NOW()
					)");
					
					if ( $result )
					{
						return array (
							"status"  => "true",
							"message" => "Image has been successfully uploaded! Please wait..."
						);
						die();
					}
					else 
					{
						return array (
							"status"  => "false",
							"message" => "There was a error with sql... Contact support!",
							"input"   => "image"
						);
						die();
					}
					
				}
				else
				{
					return array (
						"status"  => "false",
						"message" => "There was a error with moving file.. Contact support!",
						"input"   => "image"
					);
					die();
				}
			}
			
			return array (
				"status"  => "false",
				"message" => "{$loc}",
				"input"   => "image"
			);
			die();
		}
		
		public function retriveImgListForId( $id )
		{
			$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
			$result = $this->db->fetchAll("SELECT * FROM storage_images_data 
			WHERE imageid='{$id}' AND garbaged='false'");
			
			foreach ( $result as $image )
			{
				if ( $image->fakename )
				{
					$name = $image->fakename;
				}
				else
				{
					$exp = explode ( ".", $image->filename );
					$name = $exp[0];
				}
				$linkweb =  self::$system->enviroment->url . self::$image_loc . $image->imageid . "/" . $image->filename;
				$linkcore = self::$image_loc . $image->imageid . "/" . $image->filename;
				?>
					<li>
						<a rel="lightbox" href="<?php echo $linkweb; ?>" src="<?php echo $linkweb; ?>" title="Name: <?php echo $name; ?> - Size: <?php echo $image->size; ?> - Type: <?php echo $image->type; ?>"><?php echo $name; ?></a>
						<p>Type: <?php echo $image->type; ?> - Size: <?php echo $image->size; ?> <a href="#" onclick="deleteImage('<?php echo $linkcore; ?>', '<?php echo $image->id; ?>');" title="Delete current <?php echo $name; ?>">[ delete image ]</a></p>
					</li>
				<?php
				
			}
		}
		
		public function deleteImageFromId( $id )
		{
			// Ok firstly we need to delete image
			// than we need to delete sql query record
			// and return message
			$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
			$row = $this->db->fetchRow("SELECT * FROM storage_images_data WHERE id='{$id}'");
			
			$linkcore = self::$image_loc . $row->imageid . "/" . $row->filename;
			
			if ( file_exists( $linkcore ) )
			{
				unlink( $linkcore );	
			}
			
			// lets go delete record
			
			$del = $this->db->query( "DELETE FROM storage_images_data WHERE id='{$id}'" );
			
			if ( $del )
			{
				return array (
					"status" => "true",
					"message" => "Image successfully deleted! Please wait..."
				);
			}
			
			return array (
				"status" => "false",
				"message" => "Image cannot be deleted... SQL error!"
			);
		}
		
		public function getImageById ( $id )
		{
			$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
			return $result = $this->db->fetchRow( "SELECT * FROM storage_images WHERE id='{$id}'" );
		}
		
		public function getListOfImages()
		{
			$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
			return $result = $this->db->fetchAll( "SELECT * FROM storage_images WHERE garbaged='false'" );
		}
	}

